package com.wis.bolt.risk;

import com.alibaba.fastjson.JSONObject;
import com.wis.tools.CommonUtiles;
import com.wis.tools.RiskUtiles;
import org.apache.commons.lang.StringUtils;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: traffic_wis
 * @author: fan
 * @Date: Created in 2018/12/17 14:35
 * @Modified By:
 */
public class MagicToDianBolt extends BaseRichBolt {
    private OutputCollector collector = null;
    private JSONObject jsonLatLon;

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) {
        this.collector = collector;
        jsonLatLon = new CommonUtiles().getHttpJsonObject(map.get("queryLonLat").toString());
    }

    @Override
    public void execute(Tuple tuple) {
        // key为：标准key
        String key = tuple.getStringByField("key");
        // value：要素值+相态值+桩点
        // 0_300_G1_710
        String value = tuple.getStringByField("value");

        try {
            if (value.equals("over")) {
                this.collector.emit(new Values(key, "1_1_" + key.substring(1, 2) + "_over"));
            } else if (StringUtils.isNotBlank(value)/* && value.length() > 4*/) {
                List tupleQueue = Arrays.asList(value.split(",", -1));
                if (!tupleQueue.isEmpty() && tupleQueue.size() > 0) {
                    String str = new RiskUtiles().genPointDataToJson(tupleQueue, jsonLatLon);
                    if (str != null) {
                        // System.out.println("路段点数据key为：" + key + "-----value为：" + str);
                        this.collector.emit(new Values(key, str));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.collector.ack(tuple);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("key", "value"));
    }


}
